package com.smartsystem.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * MyBatis-Plus配置类
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 分页插件配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 自动填充配置
     */
    @Slf4j
    @Component
    public static class MyMetaObjectHandler implements MetaObjectHandler {

        /**
         * 获取当前登录用户ID
         * @return 用户ID，如果未登录则返回默认值1L
         */
        private Long getCurrentUserId() {
            try {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if (authentication != null && authentication.isAuthenticated() 
                    && !"anonymousUser".equals(authentication.getName())) {
                    // TODO: 这里应该通过用户名查询数据库获取真实的用户ID
                    // 目前暂时返回默认值，后续需要完善
                    return 1L;
                }
            } catch (Exception e) {
                log.warn("获取当前用户ID失败: {}", e.getMessage());
            }
            // 未登录或获取失败时使用默认值
            return 1L;
        }

        @Override
        public void insertFill(MetaObject metaObject) {
            // 创建时间自动填充
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
            this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
            
            // 从当前登录用户获取用户ID
            Long currentUserId = getCurrentUserId();
            this.strictInsertFill(metaObject, "createBy", Long.class, currentUserId);
            this.strictInsertFill(metaObject, "updateBy", Long.class, currentUserId);
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            // 更新时间自动填充
            this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
            
            // 从当前登录用户获取用户ID
            Long currentUserId = getCurrentUserId();
            this.strictUpdateFill(metaObject, "updateBy", Long.class, currentUserId);
        }
    }
}